package com.yesep.learn.netty.tcp.client;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Random;

import com.yesep.learn.netty.tcp.protocol.common.SYS_TYPE;
import com.yesep.learn.netty.tcp.protocol.session.Command;
import com.yesep.learn.netty.tcp.protocol.util.CommandUtil;

import cn.hutool.core.date.DateUtil;

/**
 * @Description: 
 */
public class YaClientTest {
	public static final String DATETIME_FMT = "yyyy-MM-dd HH:mm:ss";
	public static final String[] MN_LIST = new String[] { "YA001", "YA002", "YA003", "YA004", "YA005" };
	/*	pH	w01001
		浊度	w01003
		溶解氧	w01009
		电导率	w01014
		叶绿素a	w01016
		生化需氧量	w01017
		化学需氧量	w01018
		总氮	w21001
		总磷	w21011
	*/

	public static final String[] FACTOR_LIST = new String[] { "w01001", "w01003", "w01009", "w01014", "w01016", "w01017", "w01018", "w21001", "w21011" };
	public static final Double[] FACTOR_MIN = new Double[] { 6d, 200d, 5d, 100d, 3d, 0d, 8d, 2d, 0d };
	public static final Double[] FACTOR_MAX = new Double[] { 8d, 500d, 9d, 300d, 100d, 6d, 30d, 10d, 0.2d };

	public static String nextDouble(final double min, final double max) {
		double newDoublue = min + ((max - min) * new Random().nextDouble());
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(newDoublue);
	}

	public static void main(String[] args) {
		String ip = "39.98.81.88";
		Integer port = 8888;
		long now = System.currentTimeMillis();
		Date date = DateUtil.parse("2019-08-29 00:00:30", DATETIME_FMT);
		NettyClient client = null;
		try {
			client = new NettyClient(ip, port);
			while (true) {//
				if (date.getTime() > now) {
					break;
				}
				for (String mn : MN_LIST) {
					Command cmd = new Command(SYS_TYPE.WATER.getCode(), "2051", "123456", mn, 5);
					cmd.addCPParam("DataTime", DateUtil.format(date, CommandUtil.QN_DT_FMT));
					for (int i = 0; i < FACTOR_LIST.length; i++) {
						cmd.addCPData(FACTOR_LIST[i], "Rtd", nextDouble(FACTOR_MIN[i], FACTOR_MAX[i]));
					}
					String msg = cmd.toString();
					System.out.println(msg);
					client.writeAndFlush(msg);
					Thread.sleep(1000);
				}
				date = DateUtil.offsetHour(date, 4);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != client) {
				try {
					client.shutdown();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
